<?php
// +----------------------------------------------------------------------
// | RXThinkCMF框架 [ RXThinkCMF ]
// +----------------------------------------------------------------------
// | 版权所有 2017~2021 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: 牧羊人 <1175401194@qq.com>
// +----------------------------------------------------------------------

namespace App\Http\Controllers;

use App\Exports\Export;
use App\Models\LevelModel;
use App\Services\LevelService;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 职级管理-控制器
 * @author 牧羊人
 * @since 2020/11/11
 * Class LevelController
 * @package App\Http\Controllers
 */
class LevelController extends Backend
{

    /**
     * 构造函数
     * @author 牧羊人
     * @since 2020/11/11
     * LevelController constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->model = new LevelModel();
        $this->service = new LevelService();
    }

    /**
     * 获取职级列表
     * @return mixed
     * @since 2020/11/11
     * @author 牧羊人
     */
    public function getLevelList()
    {
        $result = $this->service->getLevelList();
        return $result;
    }

    /**
     * 导出Excel
     * @author 牧羊人
     * @since 2021/4/10
     */
    public function exportExcel()
    {
        // 参数
        $param = request()->all();
        // 文件名称
        $fileName = date('YmdHis') . '.xlsx';
        // 表格头
        $header = ['职级ID', '职级名称', '职级状态', '排序'];
        // 获取数据源
        $result = $this->model->where("mark", "=", 1)->get()->toArray();
        $list = [];
        if (!empty($result)) {
            foreach ($result as $key => $val) {
                $data = [];
                $data['id'] = $val['id'];
                $data['name'] = $val['name'];
                $data['status'] = $val['status'] == 1 ? "在用" : "停用";
                $data['sort'] = $val['sort'];
                $list[] = $data;
            }
        }
        // 保存文件
        if (!Excel::store(new Export($list, $header, "职级列表"), "" . $fileName)) {
            return message(MESSAGE_FAILED, false);
        }
        // 移动文件
        copy(storage_path("app") . "/" . $fileName, UPLOAD_TEMP_PATH . "/" . $fileName);
        // 下载地址
        $fileUrl = get_image_url(str_replace(ATTACHMENT_PATH, "", UPLOAD_TEMP_PATH) . "/" . $fileName);
        return message(MESSAGE_OK, true, $fileUrl);
    }

}
